<template>
	<div class="table">
		<div class="crumbs">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item>
					<i class="el-icon-lx-cascades"></i>路由管理
				</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="container">
			<div class="handle-box">
				<el-row>
					<el-button type="success" class="handle-del mr10" @click="routeModalOpen('add')">新增路由</el-button>
					<el-input v-model="searchText" placeholder="筛选关键词" class="handle-input mr10"></el-input>
					<el-button type="primary" @click="search">查询</el-button>
					<el-button type="primary" style="float:right;" @click="check()">路由验证</el-button>
					<el-button type="primary" style="float:right;" @click="refresh()">刷新接口</el-button>
				</el-row>
			</div>
			<!-- @row-click="toggleRowExpansion" -->
			<el-table :data="tableData" ref="table" :row-key="rowKey" :expand-row-keys="expands" @cell-click="handleCellClick" stripe border style="width: 100%">
				<el-table-column type="expand">
					<template slot-scope="props">
						<el-table :data="props.row.filterList" stripe border style="width: 100%">
							<el-table-column prop="filterName" label="过滤器名称" width="180"></el-table-column>
							<el-table-column prop="filterValue" label="过滤器值" width="180"></el-table-column>
							<el-table-column prop="filterKey" label="过滤器Key" width="180"></el-table-column>
							<el-table-column prop="filterKeyExt" label="过滤器扩展key" width="180"></el-table-column>
							<el-table-column prop="filterValueExt" label="过滤器扩展值" width="180"></el-table-column>
							<el-table-column label="操作" width="180">
								<template slot-scope="scope">
									<el-button type="primary" @click="filterModalOpen('modify',scope)">修改</el-button>
									<el-button type="danger" @click="delFilter(scope.row)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</template>
				</el-table-column>
				<el-table-column prop="routeName" label="路由名称" width="160"></el-table-column>
				<el-table-column prop="path" label="路径" width="180"></el-table-column>
				<!-- <el-table-column prop="order" label="order" width="60"></el-table-column> -->
				<el-table-column prop="uri" label="URI" width="180"></el-table-column>
				<el-table-column label="创建时间" width="180">
					<template slot-scope="scope">{{scope.row.gmtCreate | moment('YYYY-MM-DD HH:mm:ss')}}</template>
				</el-table-column>
				<el-table-column label="更新时间" width="180">
					<template slot-scope="scope">{{scope.row.gmtModified | moment('YYYY-MM-DD HH:mm:ss')}}</template>
				</el-table-column>
				<el-table-column label="操作" width="260">
					<template slot-scope="scope">
						<el-button type="success" @click="filterModalOpen('add',scope)">新增过滤器</el-button>
						<el-button type="primary" @click="routeModalOpen('modify',scope)">修改</el-button>
						<el-button type="danger" @click="routeDel(scope)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination background @current-change="handleCurrentChange" layout="prev, pager, next" :total="pageOption.total" :page-size="pageOption.size"></el-pagination>
			</div>
		</div>
		<!-- 路由弹出框 -->
		<el-dialog @close="dialogClose('routeModalForm')" :title="routeTitle" :visible.sync="routeModal" width="32%">
			<el-form ref="routeModalForm" :model="routeModalForm" :rules="routeRules" label-width="100px">
				<el-form-item label="路由名称" prop="routeName">
					<el-input v-model="routeModalForm.routeName" :disabled="!routeIsAdd"></el-input>
				</el-form-item>
				<el-form-item label="映射路径" prop="path">
					<el-input v-model="routeModalForm.path"></el-input>
				</el-form-item>
				<el-form-item label="映射URL" prop="uri">
					<el-input v-model="routeModalForm.uri"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
        <el-button @click="routeModal = false">取 消</el-button>
        <el-button v-if="routeIsAdd" type="primary" @click="routeAdd('routeModalForm')">确 定</el-button>
        <el-button v-else type="primary" @click="routeModify('routeModalForm')">确 定</el-button>
      </span>
		</el-dialog>
		<!-- 路由查看弹出框 -->
		<el-dialog title="查看路由" :visible.sync="routeViewModal" width="60%">
			<el-row :gutter="20">
				<el-col :span="4">
					<div class="grid-content bg-purple">路由名称</div>
				</el-col>
				<el-col :span="8">
					<div class="grid-content bg-purple">{{routeView.routeName}}</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">映射路径</div>
				</el-col>
				<el-col :span="8">
					<div class="grid-content bg-purple">{{routeView.path}}</div>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="4">
					<div class="grid-content bg-purple">映射URL</div>
				</el-col>
				<el-col :span="8">
					<div class="grid-content bg-purple">{{routeView.uri}}</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">顺序</div>
				</el-col>
				<el-col :span="8">
					<div class="grid-content bg-purple">{{routeView.order}}</div>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="4">
					<div class="grid-content bg-purple">创建时间</div>
				</el-col>
				<el-col :span="8">
					<div class="grid-content bg-purple">{{routeView.gmtCreate | moment('YYYY-MM-DD HH:mm:ss')}}</div>
				</el-col>
				<el-col :span="4">
					<div class="grid-content bg-purple">更新时间</div>
				</el-col>
				<el-col :span="8">
					<div class="grid-content bg-purple">{{routeView.gmtModified | moment('YYYY-MM-DD HH:mm:ss')}}</div>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="24">
					<div class="grid-content bg-purple">过滤器</div>
				</el-col>
			</el-row>
			<el-collapse accordion>
				<el-collapse-item v-for="filterItem in routeView.filterList" :title="filterItem.filterName" :key="filterItem.id" :name="filterItem.id">
					<el-row :gutter="20">
						<el-col :span="5">
							<div class="grid-content bg-purple">过滤器key值</div>
						</el-col>
						<el-col :span="7">
							<div class="grid-content bg-purple">{{filterItem.filterKey}}</div>
						</el-col>
						<el-col :span="5">
							<div class="grid-content bg-purple">过滤器value值</div>
						</el-col>
						<el-col :span="7">
							<div class="grid-content bg-purple">{{filterItem.filterValue}}</div>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="5">
							<div class="grid-content bg-purple">过滤器扩展信息key</div>
						</el-col>
						<el-col :span="7">
							<div class="grid-content bg-purple">{{filterItem.filterKeyExt||'&nbsp;'}}</div>
						</el-col>
						<el-col :span="5">
							<div class="grid-content bg-purple">过滤器扩展信息值</div>
						</el-col>
						<el-col :span="7">
							<div class="grid-content bg-purple">{{filterItem.filterValueExt||'&nbsp;'}}</div>
						</el-col>
					</el-row>
					<el-row :gutter="20">
						<el-col :span="5">
							<div class="grid-content bg-purple">创建时间</div>
						</el-col>
						<el-col :span="7">
							<div class="grid-content bg-purple">{{filterItem.gmtCreate | moment('YYYY-MM-DD HH:mm:ss')}}</div>
						</el-col>
						<el-col :span="5">
							<div class="grid-content bg-purple">更新时间</div>
						</el-col>
						<el-col :span="7">
							<div class="grid-content bg-purple">{{filterItem.gmtModified | moment('YYYY-MM-DD HH:mm:ss')}}</div>
						</el-col>
					</el-row>
				</el-collapse-item>
			</el-collapse>
			<span slot="footer" class="dialog-footer">
        <el-button @click="routeViewModal = false">关 闭</el-button>
      </span>
		</el-dialog>
		<!-- 过滤器弹出框 -->
		<el-dialog @close="dialogClose('filterForm')" :title="filterTitle" :visible.sync="filterModal" width="40%">
			<el-form ref="filterForm" :rules="filterRules" :model="filterModalForm" label-width="180px">
				<el-form-item label="过滤器名称" prop="filterName">
					<el-input v-model="filterModalForm.filterName"></el-input>
				</el-form-item>
				<el-form-item label="过滤器KEY值" prop="filterKey">
					<el-input v-model="filterModalForm.filterKey"></el-input>
				</el-form-item>
				<el-form-item label="过滤器值" prop="filterValue">
					<el-input v-model="filterModalForm.filterValue"></el-input>
				</el-form-item>
				<el-form-item label="过滤器扩展信息KEY值" prop="filterKeyExt">
					<el-input v-model="filterModalForm.filterKeyExt"></el-input>
				</el-form-item>
				<el-form-item label="过滤器扩展信息值" prop="filterValueExt">
					<el-input v-model="filterModalForm.filterValueExt"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
        <el-button @click="filterModal = false">取消</el-button>
        <el-button type="primary" @click="filterModalSave('filterForm')">确定</el-button>
      </span>
		</el-dialog>
	</div>
</template>

<script>
	/*!
	 * Routes 路由管理组件
	 * 2018-12-14 梁誉
	 * 创建了Routes组件
	 * 2018-12-20 梁誉和陈旭
	 * 合并代码，ly：路由功能，查询功能，分页功能 cx：过滤器功能，刷新接口功能，路由验证功能
	 */
	export default {
		name: 'routeManage',
		data() {
			return {
				//搜索框内的值
				searchText: '',
				//路由管理下的table表格的数据
				tableData: [],
				//获取当前行
				rowId: '',
				expands: [],
				//分页配置信息
				pageOption: {
					total: 0,
					size: 10,
					current: 1,
					sidx: 'gmt_modified',
					sord: 'asc'
				},
				//新增路由弹窗标识符，相当于id，通过控制true和false来表示显示和隐藏
				routeTitle: '新增路由',
				routeSelectId: null,
				routeIsAdd: true,
				routeModal: false,
				routeViewModal: false,
				routeModalForm: {
					routeName: '',
					path: '',
					uri: '',
					order: '0',
					filterList: []
				},
				routeView: {
					routeName: '',
					path: '',
					uri: '',
					order: '0',
					gmtCreate: new Date(),
					gmtModified: new Date(),
					filterList: []
				},
				//新增路由里新增过滤器
				filterTitle: '新增过滤器',
				filterModal: false,
				filterIsAdd: false,
				filterId: '',
				routeId: '',
				filterModalForm: {
					filterName: '',
					filterKey: '',
					filterValue: '',
					filterKeyExt: '',
					filterValueExt: ''
				},
				//路由验证规则
				routeRules: {
					routeName: [{
						required: true,
						message: '请输入路由名称',
						trigger: 'blur'
					}],
					path: [{
						required: true,
						message: '请输入路由前缀',
						trigger: 'blur'
					}],
					uri: [{
						required: true,
						message: '请输入url路径',
						trigger: 'blur'
					}]
				},
				//过滤器验证规则
				filterRules: {
					filterName: [{
						required: true,
						message: '请输入过滤器名称',
						trigger: 'blur'
					}],
					filterKey: [{
						required: true,
						message: '请输入过滤器KEY值',
						trigger: 'blur'
					}],
					filterValue: [{
						required: true,
						message: '请输入过滤器值',
						trigger: 'blur'
					}]
				}
			}
		},
		methods: {
			/** 
			 * 切换行展开状态 
			 */
			toggleRowExpansion(row) {
				this.expands = []
				this.expands.push(row.id)
			},
			/** 
			 * table 行的key 
			 */
			rowKey(row) {
				return row.id
			},
			/** 
			 * 路由接口刷新 
			 */
			refresh() {
				this.$axios.put('/route/refresh').then(res => {
					if(res.data.success) {
						this.$message({
							message: res.data.msg,
							type: 'success'
						})
					} else {
						this.$message({
							message: res.data.msg,
							type: 'error'
						})
					}
				}).catch(err => console.log(err))
			},
			/** 
			 * 路由接口检查 
			 */
			check() {
				this.$axios.get('/actuator/gateway/routes').then(res => {
					if(res.status == 200) {
						this.$message({
							message: '代表路由配置成功',
							type: 'success'
						})
					} else {
						this.$message({
							message: '代表路由配出错',
							type: 'error'
						})
					}
				}).catch(err => console.log(err))
			},
			/** 
			 * 获取路由列表
			 * @param routeName {String} 路由名称（非必传参数，如传值则根据路由名称获取信息）
			 * @param showMsg {Boolean} 是否显示加载成功提示框
			 */
			getRouteList(routeName, showMsg) {
				const params = this.pageOption
				params['routeName'] = routeName || ''
				return this.$axios.get('/route/page', {
					params: params
				}).then(res => {
					if(res.data.success) {
						this.tableData = res.data.data.records
						this.pageOption.total = res.data.data.total
						if(showMsg) {
							this.$message({
								message: res.data.msg,
								type: 'success'
							})
						}
					} else {
						this.$message({
							message: res.data.msg,
							type: 'error'
						})
					}
				}).catch(err => console.log(err))
			},
			/** 
			 * 分页导航
			 * @param val {null} 不需要传,返回当前页数
			 */
			handleCurrentChange(val) {
				this.pageOption.current = val
				const searchText = this.searchText
				this.getRouteList(searchText)
			},
			/**
			 * 搜索框查询过滤方法
			 */
			search() {
				const searchText = this.searchText
				this.getRouteList(searchText, true)
			},
			/** 
			 * 点击单元格触发
			 * @param row {null} 不需要传，返回当前行信息
			 * @param column {null} 不需要传，返回当前列信息
			 * @param cell {null} 不需要传，返回选中的dom节点
			 * @param event {null} 不需要传，返回当前event
			 */
			handleCellClick(row, column, cell, event) {
				const property = column.property
				if(property === 'routeName') {
					this.routeSelectId = row.id
					this.getRouteView()
				}
			},
			/**
			 * 路由信息查询
			*/
			getRouteView() {
				const url = '/route/' + this.routeSelectId
				this.$axios.get(url).then(res => {
					if(res.data.success) {
						this.routeView = res.data.data
						this.routeViewModal = true
						this.$message({
							message: res.data.msg,
							type: 'success'
						})
					} else {
						this.$message({
							message: res.data.msg,
							type: 'error'
						})
					}
				}).catch(err => console.log(err))
			},
			/** 
			 * 打开路由模态窗口
			 * @param opt {String} 'add'和'modify',新增和修改的模态窗口
			 * @param scope {Object} 获取到当前单元格信息
			 */
			routeModalOpen(opt, scope) {
				if(opt === 'add') {
					this.routeTitle = '新增路由'
					this.routeIsAdd = true
					this.routeSelectId = null
					this.routeModalForm.routeName = ''
					this.routeModalForm.path = ''
					this.routeModalForm.uri = ''
				} else {
					this.routeTitle = '修改路由'
					this.routeIsAdd = false
					this.routeSelectId = scope.row.id
					this.routeModalForm.routeName = scope.row.routeName
					this.routeModalForm.path = scope.row.path
					this.routeModalForm.uri = scope.row.uri
				}
				this.routeModal = true
			},
			/** 
			 * 新增路由保存，将新增路由的信息上传到后台
			 * @param formName {String} 提交的form表单的model
			 */
			routeAdd(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						const params = this.routeModalForm
						this.$axios.post('/route', params).then(res => {
							// console.log(res + '----------------------asd')
							if(res.data.success) {
								//新增成功后重新加载页面数据
								this.getRouteList()
								//关闭路由操作页面
								this.routeModal = false
								this.$message({
									message: res.data.msg,
									type: 'success'
								})
							} else {
								this.$message({
									message: res.data.msg,
									type: 'error'
								})
							}
						}).catch(err => console.log(err))
					} else {
						console.log('error submit!!')
						return false
					}
				})

			},
			/**
			 * 修改路由保存
			 * @param formName {String} 提交的form表单的model
			 */
			routeModify(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {
						// const params = this.routeModalForm
						const params = {
							routeName: this.routeModalForm.routeName,
							path: this.routeModalForm.path,
							uri: this.routeModalForm.uri
						}
						params['id'] = this.routeSelectId
						this.$axios.put('/route', params).then(res => {
							if(res.data.success) {
								//修改成功后重新加载页面数据
								this.getRouteList()
								//关闭路由操作页面
								this.routeModal = false
								this.$message({
									message: res.data.msg,
									type: 'success'
								})
							} else {
								this.$message({
									message: res.data.msg,
									type: 'error'
								})
							}
						}).catch(err => console.log(err))
					} else {
						console.log('error submit!!')
						return false
					}
				})

			},
			/**
			 * 删除路由
			 * @param scope {Object} 获取到当前单元格信息
			 */
			routeDel(scope) {
				console.log(scope)
				const url = '/route/' + scope.row.id
				this.$confirm('是否删除过滤器', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					/* 确定之后返回删除请求 */
					return this.$axios.delete(url)
				}).then(res => {
					if(res.data.success) {
						//删除成功后重新加载页面数据
						this.getRouteList()
						//关闭路由操作页面
						this.routeDelModal = false
						this.$message({
							message: res.data.msg,
							type: 'success'
						})
					} else {
						this.$message({
							message: res.data.msg,
							type: 'error'
						})
					}
				}).catch(() => {
					console.log('用户取消')
				})
			},
			/**
			 * 新增过滤器 
			 */
			addFilter() {
				const params = this.filterModalForm
				params['routeId'] = this.routeId
				return this.$axios
					.post('/filter', params)
					.then(res => {
						if(res.data.success) {
							this.$message({
								message: res.data.msg,
								type: 'success'
							})
						} else {
							this.$message({
								message: res.data.msg,
								type: 'error'
							})
						}
					}).catch(err => console.log(err))
			},
			/** 
			 * 修改过滤器 
			 */
			modifyFilter() {
				const params = this.filterModalForm
				params['filterId'] = this.filterId
				return this.$axios
					.put('/filter', params)
					.then(res => {
						if(res.data.success) {
							this.$message({
								message: res.data.msg,
								type: 'success'
							})
						} else {
							this.$message({
								message: res.data.msg,
								type: 'error'
							})
						}
					}).catch(err => console.log(err))
			},
			/**
			 * 删除过滤器
			 */
			delFilter(scope) {
				this.$confirm('是否删除过滤器', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					/* 确定之后返回删除请求 */
					return this.$axios.delete(`/filter/${scope.id}`)
				}).then(res => {
					if(res.data.success) {
						this.$message({
							message: res.data.msg,
							type: 'success'
						})
						/* 删除路由数据 */
						this.tableData.forEach(item => {
							item.filterList.splice(item.filterList.findIndex(item => item.id === scope.id), 1)
						})
					} else {
						this.$message({
							message: res.data.msg,
							type: 'error'
						})
					}
				}).catch(() => {
					console.log('用户取消')
				})
			},
			/**
			 * 打开过滤器模态窗口
			 * @param opt {String} 'add'和'modify',新增和修改的模态窗口
			 */
			filterModalOpen(opt, scope) {
				if(opt === 'add') {
					this.filterTitle = '新增过滤器'
					this.filterIsAdd = true
					this.routeId = scope.row.id
				} else {
					this.filterTitle = '修改过滤器'
					this.filterIsAdd = false
					this.routeId = scope.row.id
					this.filterId = scope.row.id
					this.filterModalForm.filterName = scope.row.filterName
					this.filterModalForm.filterKey = scope.row.filterKey
					this.filterModalForm.filterValue = scope.row.filterValue
					this.filterModalForm.filterKeyExt = scope.row.filterKeyExt
					this.filterModalForm.filterValueExt = scope.row.filterValueExt
				}
				this.filterModal = true
			},
			/**
			 * 过滤器表单验证，新增 or 修改
			 */
			filterModalSave(formName) {
				/* 表单通过 */
				this.$refs[formName].validate((pass, obj) => {
					if(!pass) return false
					/* 提交过滤器 */
					if(this.filterIsAdd) {
						this.addFilter().then(() => {
							/* 清空表单,关闭模态框,刷新表格 */
							// this.$refs[formName].resetFields()
							this.filterModal = false
							/* 默认展开行 */
							this.getRouteList().then(() => {
								this.$refs.table.toggleRowExpansion(this.routeId, true)
							})
						})
					} else {
						this.modifyFilter().then(() => {
							/* 清空表单,关闭模态框,刷新表格 */
							// this.$refs[formName].resetFields()
							this.filterModal = false
							this.getRouteList().then(() => {
								this.$refs.table.toggleRowExpansion(this.routeId, true)
							})
						})
					}
				})
			},
			/** 
			 * 模态框关闭回调 
			 */
			dialogClose(formName) {
				this.$refs[formName].resetFields()
			}
		},
		created() {
			this.getRouteList('', true)
		}
	}
</script>

<style scoped lang="less">
	.handle-box {
		margin-bottom: 20px;
	}
	
	.handle-select {
		width: 120px;
	}
	
	.handle-input {
		width: 300px;
		display: inline-block;
	}
	
	.del-dialog-cnt {
		font-size: 16px;
		text-align: center;
	}
	
	.table {
		width: 100%;
		font-size: 14px;
	}
	
	.red {
		color: #ff0000;
	}
	
	.el-row {
		margin-bottom: 18px;
		line-height: 32px;
		font-size: 14px;
	}
</style>